<?php

namespace App\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

class AuthFilter implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = NULL)
    {
        $validation = \Config\Services::validation();
        $token = $request->getHeaderLine("token");

        $errorsMsg = [
            'required' => 'token 获取失败',
            'is_not_unique' => 'token 验证失败',
        ];

        if (!$validation->check($token, 'required|is_not_unique[user.token]', $errorsMsg)) {
            $errors = $validation->getErrors();
            $message = array_shift($errors);

            return response()->setJSON(["data" => null, "error" => true, "message" => $message]);
        }
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = NULL)
    {
        // TODO: Implement after() method.
    }
}